package com.example.ilvuuz.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.ilvuuz.entity.User;
import com.example.ilvuuz.mapper.UserMapper;
import com.example.ilvuuz.service.UserService;
import com.example.ilvuuz.utils.JwtUtil;
import com.example.ilvuuz.utils.Md5Util;
import com.example.ilvuuz.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
@Transactional  // 添加事务管理
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void register(User user) {
        // 检查用户名是否已存在
        if (getByUsername(user.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 密码MD5加密
        user.setPassword(Md5Util.encode(user.getPassword()));
        
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        user.setCreatedtime(now);
        user.setUpdatetime(now);
        
        // 清除客户端传入的ID
        user.setId(null);
        
        // 初始化余额为0
        user.setBalance(BigDecimal.ZERO);
        
        // 保存用户
        userMapper.insert(user);
    }

    @Override
    public String login(String username, String password) {
        // 获取用户信息（直接从数据库获取，不从Redis获取）
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 验证密码
        if (!Md5Util.matches(password, user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 生成token
        String token = jwtUtil.generateToken(username);
        
        // 将用户信息存入Redis，设置60秒过期
        String redisKey = "user:" + username;
        User cacheUser = new User();
        // 只复制需要缓存的字段
        cacheUser.setId(user.getId());
        cacheUser.setUsername(user.getUsername());
        cacheUser.setAvatar(user.getAvatar());
        cacheUser.setBalance(user.getBalance());
        cacheUser.setPhone(user.getPhone());
        cacheUser.setEmail(user.getEmail());
        cacheUser.setAddress(user.getAddress());
        cacheUser.setCreatedtime(user.getCreatedtime());
        cacheUser.setUpdatetime(user.getUpdatetime());
        // 不设置密码
        redisUtil.set(redisKey, cacheUser, 60);
        
        return token;
    }

    @Override
    public User getByUsername(String username) {
        // 先从Redis中获取
        String redisKey = "user:" + username;
        Object cachedUser = redisUtil.get(redisKey);
        if (cachedUser != null) {
            // 如果是获取用户信息的请求，直接返回缓存的用户（不含密码）
            return (User) cachedUser;
        }
        
        // Redis中不存在，从数据库查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return userMapper.selectOne(wrapper);
    }
} 